package com.budwk.app.sqfwV2.service.povertyMonitoring;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.sax.handler.RowHandler;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.exception.Asserts;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.enums.SupportBusinessTypeEnum;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfwV2.dto.entity.SqfwFamilyProperty;
import com.budwk.app.sqfwV2.dto.entity.SqfwHouseholdRegistrationInfo;
import com.budwk.app.sqfwV2.dto.entity.SqfwPovertyUpload;
import com.budwk.app.sqfwV2.dto.povertyMonitoring.*;
import com.budwk.app.sqfwV2.dto.vo.HouseholdRegistrationInfoVO;
import com.budwk.app.sqfwV2.dto.vo.PovertyPersonAllowanceExcelInfo;
import com.budwk.app.sqfwV2.enums.povertyMonitoring.PovertyMonitoringLabelEnum;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.app.util.poiUtils.ExcelPicUrlConverter;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.security.utils.SecurityUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.upload.TempFile;
import org.nutz.trans.Trans;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.getTemplatePathByOS;

/**
 * @author ZY.Wang
 * @since 2024/6/16
 */
@IocBean
public class PovertyAlleviationService {

    @Inject
    private PersonInfoService personInfoService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SqfwServicerecordService sqfwServicerecordService;
    @Inject
    private SqfwWorkorderService sqfwWorkorderService;
    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private SqfwHouseholdRegistrationInfoService sqfwHouseholdRegistrationInfoService;
    @Inject
    private SqfwFamilyPropertyService sqfwFamilyPropertyService;
    @Inject
    private SqfwPovertyUploadService sqfwPovertyUploadService;

    public void saveCheckData(String userId, PovertyAlleviationSubmitDataDTO dto) {
        saveCheckData(userId, dto, false);
    }

    public void submitCheckData(String userId, PovertyAlleviationSubmitDataDTO dto) {
        saveCheckData(userId, dto, true);
    }

    /**
     * 根据人的id得到人的检查信息
     *
     * @param personInfoId 人员表id
     * @param quarter      季度
     * @param year         年份
     * @return 结果
     */
    public PovertyAlleviationSubmitDataDTO getCheckDataByPersonInfo(String personInfoId, String quarter, String year) {
        // 逻辑是这样的
        // 1、根据人员的id查询到人员的身份证号码,通过身份证号码以及以及季度的信息查询到该季度该人员的检测信息
        //    如果有信息则返回
        //    如果还是没有，那么就直接返回人员表的信息
        PersonInfo personInfo = personInfoService.fetch(personInfoId);
        String householdId = personInfo.getHouseholdId();

        // 查询该户人口
        List<Date> communityQuarterTimeRange = getCommunityQuarterTimeRange(Integer.parseInt(year), Integer.parseInt(quarter));
        Cnd cnd = Cnd.NEW().and(Sqfw_formSummary_new::getFillDate, ">=", communityQuarterTimeRange.get(0))
                .and(Sqfw_formSummary_new::getFillDate, "<=", communityQuarterTimeRange.get(1))
                .and(Sqfw_formSummary_new::getType, "=", "脱贫监测")
                .and(Sqfw_formSummary_new::getAuditStatus, "=", "submit")
                .and(" param_data ->>  'houseHoldId' ", "=", householdId);
        List<Sqfw_formSummary_new> queryFormSummaryList = sqfwFormsummaryNewService.query(cnd);

        // 这一块的目的是得到当前人的查询记录 以及 该户中已经签了名的人的信息，方便直接赋值
        Sqfw_formSummary_new queryFormSummary = null;
        PovertyAlleviationDTO queryFormSummaryDTO = null;
        PovertyAlleviationDTO haveSignatureCheckData = null;
        List<HouseholdIncomeAndPayTypeDTO> householdIncomeAndPayTypeDTOList = null;

        for (Sqfw_formSummary_new itemQueryFormSummary : queryFormSummaryList) {
            PovertyAlleviationDTO itemPovertyAlleviation = JSONObject.parseObject(itemQueryFormSummary.getParamData(), PovertyAlleviationDTO.class);
            if (itemPovertyAlleviation.getPersonInfoId().equals(personInfo.getId())) {
                queryFormSummary = itemQueryFormSummary;
                queryFormSummaryDTO = JSONObject.parseObject(queryFormSummary.getParamData(), PovertyAlleviationDTO.class);
            }
            if (StringUtils.isNotBlank(itemPovertyAlleviation.getCollectorSignature())) {
                haveSignatureCheckData = itemPovertyAlleviation;
            }
        }

        Cnd familyPropertyCnd = Cnd.NEW().and(SqfwFamilyProperty::getQuarter, "=", quarter)
                .and(SqfwFamilyProperty::getYear, "=", year)
                .and(SqfwFamilyProperty::getHouseholdId, "=", householdId);
        SqfwFamilyProperty familyProperty = sqfwFamilyPropertyService.fetch(familyPropertyCnd);
        if (familyProperty != null) {
            String familyPropertyParamDataStr = familyProperty.getParamData();
            FamilyPropertyParamDataDTO familyParamDataDTO = JSONObject.parseObject(familyPropertyParamDataStr, FamilyPropertyParamDataDTO.class);
            householdIncomeAndPayTypeDTOList = familyParamDataDTO.getHouseholdIncomeAndPayTypeDTOList();
        }


        PovertyAlleviationSubmitDataDTO resultVO = new PovertyAlleviationSubmitDataDTO();
        resultVO.setPersonInfoId(personInfoId);
        resultVO.setHouseHoldId(householdId);

        if (queryFormSummary != null) {
            resultVO.setFormSummaryId(queryFormSummary.getId());
            resultVO.setFillDate(queryFormSummary.getFillDate());
            resultVO.setAuditStatus(queryFormSummary.getAuditStatus());
        }

        // 如果是该季度第一次检测
        PovertyAlleviationDTO povertyAlleviationDTO = new PovertyAlleviationDTO();
        BeanUtil.copyProperties(personInfo, povertyAlleviationDTO);
        BeanUtil.copyProperties(queryFormSummaryDTO, povertyAlleviationDTO);
        povertyAlleviationDTO.setPersonInfoId(personInfoId);
        povertyAlleviationDTO.setName(personInfo.getName());

        // 查看其他的成员该季度是否已经签名了
        if (haveSignatureCheckData != null) {
            povertyAlleviationDTO.setCollectorSignature(haveSignatureCheckData.getCollectorSignature());
            povertyAlleviationDTO.setFarmerSignature(haveSignatureCheckData.getFarmerSignature());
        }

        if (familyProperty != null && CollectionUtil.isNotEmpty(householdIncomeAndPayTypeDTOList)) {
            List<String> typeList = householdIncomeAndPayTypeDTOList.stream().map(HouseholdIncomeAndPayTypeDTO::getType).collect(Collectors.toList());
            povertyAlleviationDTO.setIncomeSituation(Joiner.on(",").join(typeList));
            povertyAlleviationDTO.setHouseholdIncomeAndPayTypeDTOList(householdIncomeAndPayTypeDTOList);
        }

        resultVO.setPovertyAlleviation(povertyAlleviationDTO);
        return resultVO;
    }

    public Result<?> getCheckRecordByPage(HouseholdRegistrationInfoVO bean) {
        YearMonth yearMonth = YearMonth.parse(bean.getFillDate());
        // 计算当月的总天数
        int totalDays = yearMonth.lengthOfMonth();
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
        cnd.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
        cnd.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
        cnd.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
        cnd.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
        cnd.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName());
        cnd.and(Sqfw_formSummary_new::getAuditStatus, "=", "submit");
        //cnd.and("fill_date", ">=", String.format("%s-01 00:00:00", bean.getFillDate()));
        if (StringUtils.isNotBlank(bean.getHouseNumber())) {
            cnd.and("param_data ->>'houseHoldNumber'", "=", bean.getHouseNumber());
        }
        if ("desc".equals(bean.getSort())) {
            cnd.and("fill_date", ">=", "1970-01-01 00:00:00");
            cnd.and("fill_date", "<=", String.format("%s-%s 23:59:59", bean.getFillDate(), totalDays));
        } else {
            cnd.and("fill_date", "<=", String.format("%s-%s 23:59:59", bean.getFillDate(), totalDays));
        }
        cnd.orderBy("fill_date", StringUtils.isNotBlank(bean.getSort()) ? bean.getSort() : "desc");


        Pagination pagination = this.sqfwFormsummaryNewService.listPage(bean.getPageNo(), bean.getPageSize(), cnd);
        List<Sqfw_formSummary_new> list = pagination.getList(Sqfw_formSummary_new.class);
        if (list.isEmpty()) {
            return Result.data(pagination);
        }
        int count = queryLastTotal(list, bean, user);
        pagination.setTotalCount(count);
        return Result.data(pagination);
    }

    public PersonInfoEditDTO getPersonInfo(String formSummaryId) {
        Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(formSummaryId);
        if (formSummaryNew == null) return null;

        String paramDataStr = formSummaryNew.getParamData();
        PovertyAlleviationDTO povertyAlleviationDTO = JSONObject.parseObject(paramDataStr, PovertyAlleviationDTO.class);
        String idNumber = povertyAlleviationDTO.getIdNumber();

        Cnd cnd = Cnd.NEW().and(PersonInfo::getIdNumber, "=", idNumber);
        PersonInfo personInfo = personInfoService.fetch(cnd);
        if (personInfo == null) return null;
        PersonInfoEditDTO personInfoEditDTO = new PersonInfoEditDTO();
        BeanUtil.copyProperties(personInfo, personInfoEditDTO, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        personInfoEditDTO.setConditionNote(povertyAlleviationDTO.getConditionNote());
        return personInfoEditDTO;
    }

    public void editPersonData(PersonInfoEditDTO personInfoEditDTO) {
        Trans.exec(() -> {

            String userId = SecurityUtil.getUserId();

            // 第一步更新人员表数据
            String personInfoId = personInfoEditDTO.getId();
            PersonInfo personInfo = personInfoService.fetch(personInfoId);
            BeanUtil.copyProperties(personInfoEditDTO, personInfo);
            personInfoService.update(personInfo);

            // 第二部更新formSummary的数据
            String formSummaryId = personInfoEditDTO.getFormSummaryId();
            Sqfw_formSummary_new formSummaryNew = sqfwFormsummaryNewService.fetch(formSummaryId);
            String paramDataStr = formSummaryNew.getParamData();
            PovertyAlleviationDTO povertyAlleviationDTO = JSONObject.parseObject(paramDataStr, PovertyAlleviationDTO.class);
            BeanUtil.copyProperties(personInfoEditDTO, povertyAlleviationDTO);
            formSummaryNew.setParamData(JSONObject.toJSONString(povertyAlleviationDTO));
            formSummaryNew.setUpdateBy(userId);
            formSummaryNew.setUpdateDate(new Date());
            sqfwFormsummaryNewService.update(formSummaryNew);

            // 更新家庭财产表数据
            SqfwHouseholdRegistrationInfo householdRegistration = sqfwHouseholdRegistrationInfoService.fetch(personInfo.getHouseholdId());
            YearAndQuarter communityQuarter = getCommunityQuarter(formSummaryNew.getFillDate());
            FamilyPropertyParamDataDTO familyPropertyParam = getFamilyPropertyParam(communityQuarter.getYear(), communityQuarter.getQuarter(), householdRegistration.getId());
            if (familyPropertyParam != null) {
                FamilyPropertyParamDataDTO familyPropertyInfo = createFamilyPropertyInfo(householdRegistration, familyPropertyParam.getHouseholdIncomeAndPayTypeDTOList(), formSummaryNew.getFillDate());
                insertOrUpdateFamilyPropertyInfo(SecurityUtil.getUserId(), familyPropertyInfo, formSummaryNew.getFillDate(), personInfo.getHouseholdId());
            }
        });
    }

    public void deleteFormSummaryCheckData(String formSummaryId) {

        Trans.exec(() -> {
            // 删除formSummary数据
            Sqfw_formSummary_new summaryNew = sqfwFormsummaryNewService.fetch(formSummaryId);
            String paramDataStr = summaryNew.getParamData();
            PovertyAlleviationDTO paramData = JSONObject.parseObject(paramDataStr, PovertyAlleviationDTO.class);
            sqfwFormsummaryNewService.delete(formSummaryId);

            // 更新家庭财产表
            String houseHoldId = paramData.getHouseHoldId();
            SqfwHouseholdRegistrationInfo householdRegistrationInfo = sqfwHouseholdRegistrationInfoService.fetch(houseHoldId);
            // 更新户口中的核查信息
            if (paramData.getPersonnelStatus().equals(PovertyMonitoringLabelEnum.personnelStatus_one.getCode())) {
                // 只有正常的数据才会去更新户口信息
                householdRegistrationInfo.setCheckDate("");
            } else {
                // 说明之前提交的数据是死亡或者搬离，这个时候要恢复家庭表的人数
                int peopleNum = Integer.parseInt(householdRegistrationInfo.getPeopleNumber());
                householdRegistrationInfo.setPeopleNumber((peopleNum + 1) + "");
            }
            sqfwHouseholdRegistrationInfoService.update(householdRegistrationInfo);

            YearAndQuarter communityQuarter = getCommunityQuarter(summaryNew.getFillDate());
            FamilyPropertyParamDataDTO familyPropertyParam = getFamilyPropertyParam(communityQuarter.getYear(), communityQuarter.getQuarter(), houseHoldId);
            if (familyPropertyParam != null) {
                FamilyPropertyParamDataDTO familyPropertyInfo = createFamilyPropertyInfo(householdRegistrationInfo, familyPropertyParam.getHouseholdIncomeAndPayTypeDTOList(), summaryNew.getFillDate());
                insertOrUpdateFamilyPropertyInfo(SecurityUtil.getUserId(), familyPropertyInfo, summaryNew.getFillDate(), houseHoldId);
            }

            // 更新人员表信息
            String idNumber = paramData.getIdNumber();
            Cnd cnd = Cnd.NEW().and(PersonInfo::getIdNumber, "=", idNumber);
            PersonInfo personInfo = personInfoService.fetch(cnd);
            personInfo.setCheckStatus("");
            personInfo.setCheckUpdate("");
            personInfoService.update(personInfo);
        });
    }

    //----------------------------------------------------------------------------------------------
    //   下面是一些私有的方法
    //----------------------------------------------------------------------------------------------

    /**
     * 保存扶贫检查数据
     *
     * @param dto 检查dto
     */
    private void saveCheckData(String userId, PovertyAlleviationSubmitDataDTO dto, boolean submitFlag) {

        Trans.exec(() -> {
            Date fillDate = dto.getFillDate();
            if (fillDate == null) Asserts.fail("参数错误 填表时间不能为空");
            PovertyAlleviationDTO povertyAlleviation = dto.getPovertyAlleviation();

            Sys_user sysUser = sysUserService.fetch(userId);
            String unitId = sysUser.getUnitId();
            Sys_unit unit = sysUnitService.fetch(unitId);

            dto.getPovertyAlleviation().setPersonInfoId(dto.getPersonInfoId());
            dto.getPovertyAlleviation().setHouseHoldId(dto.getHouseHoldId());

            // 一、保存之前的业务逻辑数据 serviceRecord workOrder
            Sqfw_formSummary_new formSummaryNew = saveServiceRecord(sysUser, unit, dto, submitFlag);

            // 二、保存家庭财产情况表数据
            // 1、这一段的逻辑是根据时间查看家庭财产表中是否存在这一个季度的数据如果已经存在则更新，如果不存在则插入

            // 三、准备家庭财产的人口数量
            // 计算逻辑为
            // 1、查询户口表得到当前户口的人数
            // 2、比较前端传过来的数据，如果这个人以前是正常的，现在是搬离或者死亡那么人数-1
            String houseHoldId = dto.getHouseHoldId();
            SqfwHouseholdRegistrationInfo householdRegistrationInfo = sqfwHouseholdRegistrationInfoService.fetch(houseHoldId);
            int houseHoldPeopleNum = Integer.parseInt(householdRegistrationInfo.getPeopleNumber());
            String personInfoId = dto.getPersonInfoId();
            PersonInfo personInfo = personInfoService.fetch(personInfoId);
            String personOldStatus = personInfo.getLatestStatus();
            personOldStatus = Optional.ofNullable(personOldStatus).orElse(PovertyMonitoringLabelEnum.personnelStatus_one.getCode());
            String personNewStatus = povertyAlleviation.getPersonnelStatus();   // 从前端传过来的人员的状态


            // 家庭人员信息
            if (!personNewStatus.equals(PovertyMonitoringLabelEnum.personnelStatus_one.getCode()) && personOldStatus.equals(PovertyMonitoringLabelEnum.personnelStatus_one.getCode())) {    // 现在是不正常（搬离或者死亡），以前是正常情况
                houseHoldPeopleNum -= 1;
            } else if (personNewStatus.equals(PovertyMonitoringLabelEnum.personnelStatus_one.getCode()) && !personOldStatus.equals(PovertyMonitoringLabelEnum.personnelStatus_one.getCode())) { // 以前是不正常的，现在是正常的情况（还是可能会出现这种情况的，比如一个人上一个季度搬走了，这一个季度又回来了，你说惊喜不）
                houseHoldPeopleNum += 1;
            }
            householdRegistrationInfo.setPeopleNumber(houseHoldPeopleNum + "");
            householdRegistrationInfo.setUpdateId(sysUser.getId());
            householdRegistrationInfo.setUpdateTime(LocalDateTime.now());

            if (formSummaryNew.getAuditStatus().equals("submit")) {
                FamilyPropertyParamDataDTO familyPropertyInfo = createFamilyPropertyInfo(householdRegistrationInfo, povertyAlleviation.getHouseholdIncomeAndPayTypeDTOList(), dto.getFillDate());
                insertOrUpdateFamilyPropertyInfo(userId, familyPropertyInfo, formSummaryNew.getFillDate(), dto.getHouseHoldId());
            }

            // 查询该户所有的人是不是已经全部核查结束
            String curHouseholdPeopleNumStr = householdRegistrationInfo.getPeopleNumber();
            List<Date> timeRange = getCommunityQuarterTimeRange(fillDate);
            Cnd allPersonCnd = Cnd.NEW().and(Sqfw_formSummary_new::getType, "=", "脱贫监测")
                    .and(Sqfw_formSummary_new::getFillDate, ">=", timeRange.get(0))
                    .and(Sqfw_formSummary_new::getFillDate, "<=", timeRange.get(1))
                    .and("param_data ->> 'houseHoldId' ", "=", houseHoldId)
                    .and(Sqfw_formSummary_new::getAuditStatus, "=", "submit");

            List<Sqfw_formSummary_new> submitPersonFormSummaryList = sqfwFormsummaryNewService.query(allPersonCnd);
            int submitPersonCount = submitPersonFormSummaryList.size();

            if (submitPersonCount >= Integer.parseInt(curHouseholdPeopleNumStr)) {
                householdRegistrationInfo.setCheckDate(DateUtil.format(fillDate, "yyyy-MM"));
            } else {
                householdRegistrationInfo.setCheckDate("");
            }
            sqfwHouseholdRegistrationInfoService.update(householdRegistrationInfo);

            // 这里要将所有人的家庭财产收入更新一下
            for (Sqfw_formSummary_new personSubmitFormSummary : submitPersonFormSummaryList) {
                String paramData = personSubmitFormSummary.getParamData();
                PovertyAlleviationDTO personPoverty = JSONObject.parseObject(paramData, PovertyAlleviationDTO.class);
                personPoverty.setHouseholdIncomeAndPayTypeDTOList(dto.getPovertyAlleviation().getHouseholdIncomeAndPayTypeDTOList());
                personSubmitFormSummary.setParamData(JSONObject.toJSONString(personPoverty));
                personSubmitFormSummary.setUpdateDate(new Date());
                sqfwFormsummaryNewService.update(personSubmitFormSummary);
            }

            // 也需要将人的状态改变
            if (formSummaryNew.getAuditStatus().equals("submit")) {
                personInfo.setLatestStatus(personNewStatus);
                personInfo.setUpdateBy(sysUser.getId());
                personInfo.setUpdateDate(LocalDateTime.now());
                personInfo.setCheckStatus(DateUtil.format(dto.getFillDate(), "yyyy-MM"));
                personInfo.setCheckUpdate(DateUtil.format(dto.getFillDate(), "yyyy-MM"));
                if (StringUtils.isBlank(personInfo.getPhone())
                        && StringUtils.isNotBlank(dto.getPovertyAlleviation().getPhone())) {
                    personInfo.setPhone(dto.getPovertyAlleviation().getPhone());
                }
                if (dto.getPovertyAlleviation().getSupportIncome() != null) {
                    personInfo.setSupportIncome(dto.getPovertyAlleviation().getSupportIncome());
                }
                personInfoService.update(personInfo);
            }
        });
    }

    /**
     * 保存之前的业务逻辑数据
     *
     * @param sysUser 系统用户
     */
    private Sqfw_formSummary_new saveServiceRecord(Sys_user sysUser, Sys_unit unit, PovertyAlleviationSubmitDataDTO dto, boolean submitFlag) {

        PovertyAlleviationDTO povertyAlleviation = dto.getPovertyAlleviation();

        if (StringUtils.isBlank(povertyAlleviation.getHouseHoldNumber()) || StringUtils.isBlank(povertyAlleviation.getIdNumber())) {
            Asserts.fail("身份证号或户口编号为空");
        }
        povertyAlleviation.setHouseHoldId(dto.getHouseHoldId());

        Sqfw_formSummary_new formSummaryNew = new Sqfw_formSummary_new();
        if (StringUtils.isNotBlank(dto.getFormSummaryId())) {
            formSummaryNew = sqfwFormsummaryNewService.fetch(dto.getFormSummaryId());
        }

        String formSummaryAuditStatus = submitFlag ? "submit" : "new";
        // 保存formSummary的数据
        formSummaryNew.setParamData(JSONObject.toJSONString(povertyAlleviation));
        formSummaryNew.setUpdateDate(new Date());
        formSummaryNew.setUpdateBy(sysUser.getId());
        formSummaryNew.setAuditStatus(formSummaryAuditStatus);
        formSummaryNew.setFillDate(dto.getFillDate());
        formSummaryNew.setProvince(sysUser.getProvince());
        formSummaryNew.setCity(sysUser.getCity());
        formSummaryNew.setDistrict(sysUser.getDistrict());
        formSummaryNew.setCounty(sysUser.getCounty());
        formSummaryNew.setCommunity(sysUser.getCommunity());
        formSummaryNew.setUpdateUserName(sysUser.getUsername());
        formSummaryNew.setUpdateUserPhone(sysUser.getLoginname());

        if (StringUtils.isBlank(formSummaryNew.getId())) {
            // 首先保存serviceRecord数据 如果这个数据是
            Sqfw_servicerecord serviceRecord = new Sqfw_servicerecord();
            serviceRecord.setCustomer_name(sysUser.getUsername());
            serviceRecord.setCustomer_phone(sysUser.getLoginname());
            serviceRecord.setType("脱贫监测");
            serviceRecord.setCustomer_need(StrFormatter.format("脱贫监测【{}】", DateUtil.format(new Date(), "MM-dd")));
            serviceRecord.setService_name(sysUser.getUsername());
            serviceRecord.setService_phone(sysUser.getLoginname());
            serviceRecord.setCreatedBy(sysUser.getId());
            serviceRecord.setCreatedAt(new Date().getTime());
            serviceRecord.setUpdatedBy(sysUser.getId());
            serviceRecord.setUpdatedAt(new Date().getTime());
            serviceRecord.setDelFlag(false);
            serviceRecord.setConnect_time(new Date());
            serviceRecord.setUser_id(sysUser.getId());
            serviceRecord.setFinishStatus("new");
            serviceRecord.setCompanyName(unit.getName());
            serviceRecord.setProvince(sysUser.getProvince());
            serviceRecord.setCity(sysUser.getCity());
            serviceRecord.setDistrict(sysUser.getDistrict());
            serviceRecord.setCounty(sysUser.getCounty());
            sqfwServicerecordService.insert(serviceRecord);

            // 然后保存workOrder
            Sqfw_workorder workOrder = new Sqfw_workorder();
            workOrder.setSqfw_id(serviceRecord.getId());
            workOrder.setUser_name(sysUser.getUsername());
            workOrder.setWk_status("new");
            workOrder.setWk_grade("0");
            workOrder.setWk_priority("take_time_complete");
            workOrder.setCreatedBy(sysUser.getId());
            workOrder.setCreateDate(new Date());
            workOrder.setUpdatedBy(sysUser.getId());
            workOrder.setUpdatedAt(new Date());
            workOrder.setDelflag(false);
            workOrder.setUser_id(sysUser.getId());
            workOrder.setFromUserId(sysUser.getId());
            workOrder.setToUserId(sysUser.getId());
            workOrder.setServiceType("脱贫监测");
            sqfwWorkorderService.insert(workOrder);

            // 然后保存一张工作流的数据
            Sqfw_completeflow completeFlow = new Sqfw_completeflow();
            completeFlow.setSqfwId(serviceRecord.getId());
            completeFlow.setWorkerId(workOrder.getId());
            completeFlow.setFileType("脱贫监测");
            completeFlow.setCreateDate(new Date());
            completeFlow.setPhone(sysUser.getLoginname());
            completeFlow.setUserId(sysUser.getId());
            completeFlow.setUserName(sysUser.getUsername());
            sqfwCompleteflowService.insert(completeFlow);

            formSummaryNew.setUnitId(unit.getId());
            formSummaryNew.setUnitName(unit.getName());
            formSummaryNew.setCreateDate(new Date());
            formSummaryNew.setCreateBy(sysUser.getId());
            formSummaryNew.setType("脱贫监测");
            formSummaryNew.setSqfwId(serviceRecord.getId());
            formSummaryNew.setWorkOrderId(workOrder.getId());
            formSummaryNew.setSqfwFlowId(completeFlow.getId());
            formSummaryNew.setCreateUserName(sysUser.getUsername());
            formSummaryNew.setCreateUserPhone(sysUser.getLoginname());
            sqfwFormsummaryNewService.insert(formSummaryNew);
        } else {
            sqfwFormsummaryNewService.update(formSummaryNew);
        }

        return formSummaryNew;
    }


    /**
     * 根据时间得到这一季度的开始时间和结束时间
     *
     * @param data 时间
     * @return 结果
     */
    public static List<Date> getCommunityQuarterTimeRange(Date data) {
        YearAndQuarter communityQuarter = getCommunityQuarter(data);
        return getCommunityQuarterTimeRange(Integer.parseInt(communityQuarter.getYear()), Integer.parseInt(communityQuarter.getQuarter()));
    }

    public static List<Date> getCommunityQuarterTimeRange(YearAndQuarter communityQuarter) {
        return getCommunityQuarterTimeRange(Integer.parseInt(communityQuarter.getYear()), Integer.parseInt(communityQuarter.getQuarter()));
    }

    /**
     * 根据用户填写的财产情况生成存储在家庭财产收入paraData中
     * <p>
     * 这个方法将在提交数据的时候进行调用
     */
    private FamilyPropertyParamDataDTO createFamilyPropertyParamData(SqfwHouseholdRegistrationInfo registrationInfo,
                                                                     List<HouseholdIncomeAndPayTypeDTO> householdIPList,
                                                                     List<PovertyAlleviationDTO> personPovList) {

        FamilyPropertyParamDataDTO familyPropertyParamDataDTO = new FamilyPropertyParamDataDTO();
        familyPropertyParamDataDTO.setHouseholdIncomeAndPayTypeDTOList(householdIPList);

        BigDecimal wage = BigDecimal.ZERO;  // 工资性收入 家庭成员所有工资收入
        BigDecimal propertyIncome = BigDecimal.ZERO;    // 财产性收入
        BigDecimal transformIncome = BigDecimal.ZERO;   // 转移性收入   每一个人的低保11项
        BigDecimal productiveIncome = BigDecimal.ZERO;  // 生产性收入
        BigDecimal productiveExpense = BigDecimal.ZERO; // 生产性支出    生产性经营支出-补贴
        BigDecimal productiveOperationExpense = BigDecimal.ZERO;    // 生产性经营支出
        BigDecimal productiveOperationSubsidy = BigDecimal.ZERO;    // 生产性经营补贴

        BigDecimal plantIndustryIncome = BigDecimal.ZERO;   // 种植业收入 123
        BigDecimal animalHusbandryIncome = BigDecimal.ZERO; // 养殖业收入 123
        BigDecimal productionAndOperationIncome = BigDecimal.ZERO;  // 生产经营性其他收入 123
        BigDecimal otherSalaryIncome = BigDecimal.ZERO; // 其他工资性收入 123
        BigDecimal publicWelfarePositionIncome = BigDecimal.ZERO;   // 公益性岗位收入 123

        BigDecimal otherTransferIncome = BigDecimal.ZERO;   //其他转移性收入

        BigDecimal plantIndustryExpense = BigDecimal.ZERO;  // 种植业支出
        BigDecimal animalHusbandryExpense = BigDecimal.ZERO;    // 养殖业支出
        BigDecimal otherExpense = BigDecimal.ZERO;  // 其他支出
        BigDecimal specialReduceAndOperationExpense = BigDecimal.ZERO;  // 补贴

        BigDecimal minLivAllow = BigDecimal.ZERO;
        BigDecimal asstFund = BigDecimal.ZERO;
        BigDecimal pension = BigDecimal.ZERO;
        BigDecimal familyPlanAllowance = BigDecimal.ZERO;
        BigDecimal ecoComp = BigDecimal.ZERO;
        BigDecimal propertyBonus = BigDecimal.ZERO;
        BigDecimal workBonus = BigDecimal.ZERO;

        BigDecimal disabilityAllowance = BigDecimal.ZERO;
        BigDecimal farmAllowance = BigDecimal.ZERO;
        BigDecimal supportIncome = BigDecimal.ZERO;
        BigDecimal otherSubsidies = BigDecimal.ZERO;

        // 根据个人数据进行计算
        for (PovertyAlleviationDTO povertyAlleviationDTO : personPovList) {
            List<PersonWorkDTO> personWorkInfoList = povertyAlleviationDTO.getPersonWorkInfoList();

            if (CollectionUtil.isNotEmpty(personWorkInfoList)) {
                for (PersonWorkDTO personWorkDTO : personWorkInfoList) {
                    String grossSalary = personWorkDTO.getGrossSalary();
                    if (StringUtils.isBlank(grossSalary)) grossSalary = "0";
                    wage = wage.add(new BigDecimal(grossSalary));

                    if (personWorkDTO.getPositionSituation().equals(PovertyMonitoringLabelEnum.positionSituation_two.getCode())) {
                        publicWelfarePositionIncome = publicWelfarePositionIncome.add(new BigDecimal(grossSalary));
                    } else {
                        otherSalaryIncome = otherSalaryIncome.add(new BigDecimal(grossSalary));
                    }
                }
            }

            minLivAllow = minLivAllow.add(Optional.ofNullable(povertyAlleviationDTO.getMinLivAllow()).orElse(BigDecimal.ZERO));
            asstFund = asstFund.add(Optional.ofNullable(povertyAlleviationDTO.getAsstFund()).orElse(BigDecimal.ZERO));
            pension = pension.add(Optional.ofNullable(povertyAlleviationDTO.getPension()).orElse(BigDecimal.ZERO));
            familyPlanAllowance = familyPlanAllowance.add(Optional.ofNullable(povertyAlleviationDTO.getFamilyPlanAllowance()).orElse(BigDecimal.ZERO));
            ecoComp = ecoComp.add(Optional.ofNullable(povertyAlleviationDTO.getEcoComp()).orElse(BigDecimal.ZERO));
            propertyBonus = propertyBonus.add(Optional.ofNullable(povertyAlleviationDTO.getPropertyBonus()).orElse(BigDecimal.ZERO));
            workBonus = workBonus.add(Optional.ofNullable(povertyAlleviationDTO.getWorkBonus()).orElse(BigDecimal.ZERO));

            disabilityAllowance = disabilityAllowance.add(Optional.ofNullable(povertyAlleviationDTO.getDisabilityAllowance()).orElse(BigDecimal.ZERO));
            farmAllowance = farmAllowance.add(Optional.ofNullable(povertyAlleviationDTO.getFarmAllowance()).orElse(BigDecimal.ZERO));
            supportIncome = supportIncome.add(Optional.ofNullable(povertyAlleviationDTO.getSupportIncome()).orElse(BigDecimal.ZERO));
            otherSubsidies = otherSubsidies.add(Optional.ofNullable(povertyAlleviationDTO.getOtherSubsidies()).orElse(BigDecimal.ZERO));
        }

        // 根据家财产情况计算
        for (HouseholdIncomeAndPayTypeDTO householdIPTypeDTO : householdIPList) {

            /** 想要查看所有的类型{@link HouseholdIncomeAndPayTypeDTO} **/
            String incomeSituationType = householdIPTypeDTO.getType();   // 对应的涉及页面中的1.财产性收入 2.生产经营性支出 3.生产经营性收入
            String categoryType = householdIPTypeDTO.getCategoryType();


            List<HouseholdIncomeAndPayDetailDTO> ipDetailList = householdIPTypeDTO.getHouseholdIncomeAndPayDetailDTOList();
            for (HouseholdIncomeAndPayDetailDTO ipDetailItem : ipDetailList) {
                BigDecimal totalPrice = Optional.ofNullable(ipDetailItem.getTotalPrice()).orElse(BigDecimal.ZERO);
                String type = ipDetailItem.getType();   // 类别1-无（财产性收入使用），2-变现，3-自产自用，4-生产性支出，5-减少生产经营性支出补贴，6-其他收入

                // 财产性收入
                if (incomeSituationType.equals(PovertyMonitoringLabelEnum.incomeSituation_1.getCode())) {
                    propertyIncome = propertyIncome.add(totalPrice);    // 财产性总收入
                }

                // 生产性经营支出
                if (incomeSituationType.equals(PovertyMonitoringLabelEnum.incomeSituation_2.getCode())) {   // 生产性支出
                    if (type.equals(PovertyMonitoringLabelEnum.type_5.getCode())) {
                        productiveOperationSubsidy = productiveOperationSubsidy.add(totalPrice);
                    } else if (type.equals(PovertyMonitoringLabelEnum.type_4.getCode())) {
                        productiveOperationExpense = productiveOperationExpense.add(totalPrice);
                    }

                    // 种植业支出
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_10.getCode())) {
                        if (type.equals(PovertyMonitoringLabelEnum.type_4.getCode())) {
                            plantIndustryExpense = plantIndustryExpense.add(totalPrice);
                        }
                    }
                    // 养殖业支出
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_11.getCode())) {
                        if (type.equals(PovertyMonitoringLabelEnum.type_4.getCode())) {
                            animalHusbandryExpense = animalHusbandryExpense.add(totalPrice);
                        }
                    }

                    // 其他支出
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_12.getCode())) {
                        if (type.equals(PovertyMonitoringLabelEnum.type_4.getCode())) {
                            otherExpense = otherExpense.add(totalPrice);
                        }
                    }
                }

                // 生产性收入
                if (incomeSituationType.equals(PovertyMonitoringLabelEnum.incomeSituation_3.getCode())) {
                    productiveIncome = productiveIncome.add(totalPrice);
                    // 种植业收入
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_8.getCode())) {
                        plantIndustryIncome = plantIndustryIncome.add(totalPrice);
                    }
                    // 养殖业收入
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_9.getCode())) {
                        animalHusbandryIncome = animalHusbandryIncome.add(totalPrice);
                    }
                    // 其他收入
                    if (categoryType.equals(PovertyMonitoringLabelEnum.categoryType_0.getCode())) {
                        productionAndOperationIncome = productionAndOperationIncome.add(totalPrice);
                    }
                }
            }
        }

        // 生产性经营支出 = 生产经营性支出-补贴
        productiveExpense = productiveOperationExpense.subtract(productiveOperationSubsidy);

        // 其他转移性收入
        otherTransferIncome = otherTransferIncome.add(disabilityAllowance).add(farmAllowance).add(supportIncome).add(otherSubsidies);
        // 转移性收入
        transformIncome = transformIncome.add(minLivAllow).add(asstFund).add(pension).add(familyPlanAllowance).add(ecoComp).add(propertyBonus).add(workBonus);

        // 家庭总收入 家庭成员所有工资收入+财产性收入+转移性收入+生产性收入+其他+其他转移性收入
        BigDecimal totalHouseHoldIncome = wage.add(propertyIncome).add(transformIncome).add(productiveIncome).add(otherSubsidies).add(otherTransferIncome);
        // 家庭纯收入 家庭总收入-生产性经营支出
        BigDecimal householdNetIncome = totalHouseHoldIncome.subtract(productiveExpense);
        // 家庭人均纯收入
        String peopleNumber = registrationInfo.getPeopleNumber();
        if (StringUtils.isBlank(peopleNumber)) peopleNumber = "0";
        BigDecimal householdNetPerIncome = householdNetIncome.divide(new BigDecimal(peopleNumber), 2, RoundingMode.HALF_UP);

        familyPropertyParamDataDTO.setTotalHouseHoldIncome(totalHouseHoldIncome);
        familyPropertyParamDataDTO.setHouseholdNetIncome(householdNetIncome);
        familyPropertyParamDataDTO.setHouseholdNetPerIncome(householdNetPerIncome);
        familyPropertyParamDataDTO.setPlantIndustryIncome(plantIndustryIncome);
        familyPropertyParamDataDTO.setAnimalHusbandryIncome(animalHusbandryIncome);
        familyPropertyParamDataDTO.setProductionAndOperationIncome(productionAndOperationIncome);
        familyPropertyParamDataDTO.setOtherSalaryIncome(otherSalaryIncome);
        familyPropertyParamDataDTO.setPublicWelfarePositionIncome(publicWelfarePositionIncome);
        familyPropertyParamDataDTO.setPropertyIncome(propertyIncome);

        familyPropertyParamDataDTO.setMinLivAllow(minLivAllow);
        familyPropertyParamDataDTO.setFamilyPlanAllowance(familyPlanAllowance);
        familyPropertyParamDataDTO.setAsstFund(asstFund);
        familyPropertyParamDataDTO.setEcoComp(ecoComp);
        familyPropertyParamDataDTO.setPension(pension);
        familyPropertyParamDataDTO.setPropertyBonus(propertyBonus);
        familyPropertyParamDataDTO.setWorkBonus(workBonus);
        familyPropertyParamDataDTO.setOtherTransferIncome(otherTransferIncome);

        familyPropertyParamDataDTO.setOtherTransferIncome(otherTransferIncome);
        familyPropertyParamDataDTO.setPlantIndustryExpense(plantIndustryExpense);
        familyPropertyParamDataDTO.setAnimalHusbandryExpense(animalHusbandryExpense);
        familyPropertyParamDataDTO.setOtherExpense(otherExpense);

        specialReduceAndOperationExpense = productiveOperationSubsidy;
        familyPropertyParamDataDTO.setSpecialReduceAndOperationExpense(specialReduceAndOperationExpense);
        return familyPropertyParamDataDTO;
    }


    private void insertOrUpdateFamilyPropertyInfo(String userId, FamilyPropertyParamDataDTO familyPropertyParamDataDTO,
                                                  Date fillDate, String householdId) {

        Sys_user sysUser = sysUserService.fetch(userId);
        SqfwHouseholdRegistrationInfo householdRegistrationInfo = sqfwHouseholdRegistrationInfoService.fetch(householdId);

        // 首先先根据季度和年进行查询该季度是否已经存在数据
        YearAndQuarter communityQuarter = getCommunityQuarter(fillDate);
        String year = communityQuarter.getYear();
        String quarter = communityQuarter.getQuarter();
        Cnd familyPropertyCnd = Cnd.NEW().and(SqfwFamilyProperty::getYear, "=", year)
                .and(SqfwFamilyProperty::getQuarter, "=", quarter)
                .and(SqfwFamilyProperty::getHouseholdId, "=", householdRegistrationInfo.getId());

        SqfwFamilyProperty familyProperty = sqfwFamilyPropertyService.fetch(familyPropertyCnd);
        if (familyProperty == null) familyProperty = new SqfwFamilyProperty();   // 家庭财产情况
        familyProperty.setHouseholdId(householdRegistrationInfo.getId());
        familyProperty.setPeopleNumber(householdRegistrationInfo.getPeopleNumber() + "");
        familyProperty.setQuarter(quarter);
        familyProperty.setYear(year);
        familyProperty.setParamData(JSONObject.toJSONString(familyPropertyParamDataDTO));
        familyProperty.setUpdateId(sysUser.getId());
        familyProperty.setUpdateTime(LocalDateTime.now());
        if (StringUtils.isBlank(familyProperty.getId())) {
            familyProperty.setCreateBy(sysUser.getId());
            familyProperty.setCreateTime(LocalDateTime.now());
            sqfwFamilyPropertyService.insert(familyProperty);
        } else {
            sqfwFamilyPropertyService.update(familyProperty);
        }
    }

    private void insertOrUpdateFamilyPropertyInfo(String userId, FamilyPropertyParamDataDTO familyPropertyParamDataDTO,
                                                  YearAndQuarter communityQuarter, String householdId) {

        Sys_user sysUser = sysUserService.fetch(userId);
        SqfwHouseholdRegistrationInfo householdRegistrationInfo = sqfwHouseholdRegistrationInfoService.fetch(householdId);

        // 首先先根据季度和年进行查询该季度是否已经存在数据
        String year = communityQuarter.getYear();
        String quarter = communityQuarter.getQuarter();
        Cnd familyPropertyCnd = Cnd.NEW().and(SqfwFamilyProperty::getYear, "=", year)
                .and(SqfwFamilyProperty::getQuarter, "=", quarter)
                .and(SqfwFamilyProperty::getHouseholdId, "=", householdRegistrationInfo.getId());

        SqfwFamilyProperty familyProperty = sqfwFamilyPropertyService.fetch(familyPropertyCnd);
        if (familyProperty == null) familyProperty = new SqfwFamilyProperty();   // 家庭财产情况
        familyProperty.setHouseholdId(householdRegistrationInfo.getId());
        familyProperty.setPeopleNumber(householdRegistrationInfo.getPeopleNumber() + "");
        familyProperty.setQuarter(quarter);
        familyProperty.setYear(year);
        familyProperty.setParamData(JSONObject.toJSONString(familyPropertyParamDataDTO));
        familyProperty.setUpdateId(sysUser.getId());
        familyProperty.setUpdateTime(LocalDateTime.now());
        if (StringUtils.isBlank(familyProperty.getId())) {
            familyProperty.setCreateBy(sysUser.getId());
            familyProperty.setCreateTime(LocalDateTime.now());
            sqfwFamilyPropertyService.insert(familyProperty);
        } else {
            sqfwFamilyPropertyService.update(familyProperty);
        }
    }

    private FamilyPropertyParamDataDTO createFamilyPropertyInfo(SqfwHouseholdRegistrationInfo registrationInfo, List<HouseholdIncomeAndPayTypeDTO> itemHouseholdIPList, Date fillDate) {
        YearAndQuarter communityQuarter = getCommunityQuarter(fillDate);
        return createFamilyPropertyInfo(registrationInfo, itemHouseholdIPList, communityQuarter);
    }

    private FamilyPropertyParamDataDTO createFamilyPropertyInfo(SqfwHouseholdRegistrationInfo registrationInfo, List<HouseholdIncomeAndPayTypeDTO> itemHouseholdIPList, YearAndQuarter communityQuarter) {
        List<Date> communityQuarterTimeRange = getCommunityQuarterTimeRange(Integer.parseInt(communityQuarter.getYear()), Integer.parseInt(communityQuarter.getQuarter()));
        Cnd cnd = Cnd.NEW().and(Sqfw_formSummary_new::getFillDate, ">=", communityQuarterTimeRange.get(0))
                .and(Sqfw_formSummary_new::getFillDate, "<=", communityQuarterTimeRange.get(1))
                .and(Sqfw_formSummary_new::getType, "=", "脱贫监测")
                .and(" param_data ->>  'houseHoldId' ", "=", registrationInfo.getId());
        List<Sqfw_formSummary_new> queryFormSummaryList = sqfwFormsummaryNewService.query(cnd);

        // 这一块主要思路是分为两大块，一个是对于家庭收支的这种一个家庭就计算一次，另外是需要计算所有家庭成员的计算
        List<PovertyAlleviationDTO> povertyAlleviationList = Lists.newArrayList();  // 每一个家庭成员提交的数据

        for (Sqfw_formSummary_new formSummaryNew : queryFormSummaryList) {
            String formSummaryParamStr = formSummaryNew.getParamData();
            PovertyAlleviationDTO paramData = JSONObject.parseObject(formSummaryParamStr, PovertyAlleviationDTO.class);
            povertyAlleviationList.add(paramData);

            if (itemHouseholdIPList == null) {
                itemHouseholdIPList = paramData.getHouseholdIncomeAndPayTypeDTOList();
            }
        }
        // 创建家庭财产数据
        FamilyPropertyParamDataDTO familyPropertyParamDataDTO = createFamilyPropertyParamData(registrationInfo, itemHouseholdIPList, povertyAlleviationList); // 家庭财产
        // 上面的这个数据是当前季度的数据，还需要查询上一季度的数据来进行整合
        YearAndQuarter lastQuarter = getCommunityLastQuarter(communityQuarter);
        if (lastQuarter != null) {
            Cnd lastQuarterCnd = Cnd.NEW().and(SqfwFamilyProperty::getQuarter, "=", lastQuarter.getQuarter())
                    .and(SqfwFamilyProperty::getYear, "=", lastQuarter.getYear())
                    .and(SqfwFamilyProperty::getHouseholdId, "=", registrationInfo.getId());
            SqfwFamilyProperty lastQuarterFamilyProperty = sqfwFamilyPropertyService.fetch(lastQuarterCnd);
            if (lastQuarterFamilyProperty != null && StringUtils.isNotBlank(lastQuarterFamilyProperty.getParamData())) {
                FamilyPropertyParamDataDTO lastYearParamDTO = JSONObject.parseObject(lastQuarterFamilyProperty.getParamData(), FamilyPropertyParamDataDTO.class);
                // 家庭总收入
                familyPropertyParamDataDTO.setTotalHouseHoldIncome(familyPropertyParamDataDTO.getTotalHouseHoldIncome().add(lastYearParamDTO.getTotalHouseHoldIncome()));
                // 家庭纯收入
                familyPropertyParamDataDTO.setHouseholdNetIncome(familyPropertyParamDataDTO.getHouseholdNetIncome().add(lastYearParamDTO.getHouseholdNetIncome()));
                // 家庭人均纯收入
                familyPropertyParamDataDTO.setHouseholdNetPerIncome(familyPropertyParamDataDTO.getHouseholdNetIncome().divide(new BigDecimal(registrationInfo.getPeopleNumber()), 2, RoundingMode.HALF_UP));
                // 种植业收入
                familyPropertyParamDataDTO.setPlantIndustryIncome(familyPropertyParamDataDTO.getPlantIndustryIncome().add(lastYearParamDTO.getPlantIndustryIncome()));
                // 养殖业收入
                familyPropertyParamDataDTO.setAnimalHusbandryIncome(familyPropertyParamDataDTO.getAnimalHusbandryIncome().add(lastYearParamDTO.getAnimalHusbandryIncome()));
                // 生产经营性其他收入
                familyPropertyParamDataDTO.setProductionAndOperationIncome(familyPropertyParamDataDTO.getProductionAndOperationIncome().add(lastYearParamDTO.getProductionAndOperationIncome()));
                // 其他工资性收入
                familyPropertyParamDataDTO.setOtherSalaryIncome(familyPropertyParamDataDTO.getOtherSalaryIncome().add(lastYearParamDTO.getOtherSalaryIncome()));
                // 公益性岗位收入
                familyPropertyParamDataDTO.setPublicWelfarePositionIncome(familyPropertyParamDataDTO.getPublicWelfarePositionIncome().add(lastYearParamDTO.getPublicWelfarePositionIncome()));
                // 财产性收入
                familyPropertyParamDataDTO.setPropertyIncome(familyPropertyParamDataDTO.getPropertyIncome().add(lastYearParamDTO.getPropertyIncome()));
                // 最低生活保障
                familyPropertyParamDataDTO.setMinLivAllow(familyPropertyParamDataDTO.getMinLivAllow().add(lastYearParamDTO.getMinLivAllow()));
                // 计划生育金
                familyPropertyParamDataDTO.setFamilyPlanAllowance(familyPropertyParamDataDTO.getFamilyPlanAllowance().add(lastYearParamDTO.getFamilyPlanAllowance()));
                // 特困人员救助供养金
                familyPropertyParamDataDTO.setAsstFund(familyPropertyParamDataDTO.getAsstFund().add(lastYearParamDTO.getAsstFund()));
                // 生态补偿金
                familyPropertyParamDataDTO.setEcoComp(familyPropertyParamDataDTO.getEcoComp().add(lastYearParamDTO.getEcoComp()));
                // 养老金或离退修金
                familyPropertyParamDataDTO.setPension(familyPropertyParamDataDTO.getPension().add(lastYearParamDTO.getPension()));
                // 产业奖励
                familyPropertyParamDataDTO.setPropertyBonus(familyPropertyParamDataDTO.getPropertyBonus().add(lastYearParamDTO.getPropertyBonus()));
                // 就业奖励
                familyPropertyParamDataDTO.setWorkBonus(familyPropertyParamDataDTO.getWorkBonus().add(lastYearParamDTO.getWorkBonus()));
                // 其他转移性收入
                familyPropertyParamDataDTO.setOtherTransferIncome(familyPropertyParamDataDTO.getOtherTransferIncome().add(lastYearParamDTO.getOtherTransferIncome()));
                // 种植业支出
                familyPropertyParamDataDTO.setPlantIndustryExpense(familyPropertyParamDataDTO.getPlantIndustryExpense().add(lastYearParamDTO.getPlantIndustryExpense()));
                // 养殖业支出
                familyPropertyParamDataDTO.setAnimalHusbandryExpense(familyPropertyParamDataDTO.getAnimalHusbandryExpense().add(lastYearParamDTO.getAnimalHusbandryExpense()));
                // 其他支出
                familyPropertyParamDataDTO.setOtherExpense(familyPropertyParamDataDTO.getOtherExpense().add(lastYearParamDTO.getOtherExpense()));
                // 专项用于减少生产性补贴
                familyPropertyParamDataDTO.setSpecialReduceAndOperationExpense(familyPropertyParamDataDTO.getSpecialReduceAndOperationExpense().add(lastYearParamDTO.getSpecialReduceAndOperationExpense()));
            }

        }

        return familyPropertyParamDataDTO;
    }

    private int queryLastTotal(List<Sqfw_formSummary_new> list, HouseholdRegistrationInfoVO bean, Sys_user user) {
        //获取分页后的最后一条数据的所在月，查询分页后最后一条数据的总数量
        Sqfw_formSummary_new summaryNew = list.get(list.size() - 1);
        Date fillDate = summaryNew.getFillDate();
        Cnd cri = Cnd.NEW();
        String fillDateStr = DateUtil.format(fillDate, DatePattern.NORM_MONTH_PATTERN);
        YearMonth lastYearMonth = YearMonth.parse(fillDateStr);
        // 计算当月的总天数
        int lastTotalDays = lastYearMonth.lengthOfMonth();
        cri.and(Sqfw_formSummary_new::getProvince, "=", user.getProvince());
        cri.and(Sqfw_formSummary_new::getCity, "=", user.getCity());
        cri.and(Sqfw_formSummary_new::getDistrict, "=", user.getDistrict());
        cri.and(Sqfw_formSummary_new::getCounty, "=", user.getCounty());
        cri.and(Sqfw_formSummary_new::getCommunity, "=", user.getCommunity());
        cri.and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName());
        cri.and(Sqfw_formSummary_new::getAuditStatus, "=", "submit");
        cri.and("fill_date", ">=", String.format("%s-01 00:00:00", fillDateStr));
        cri.and("fill_date", "<=", String.format("%s-%S 23:59:59", fillDateStr, lastTotalDays));
        if (StringUtils.isNotBlank(bean.getHouseNumber())) {
            cri.and("param_data ->>'houseHoldNumber'", "=", bean.getHouseNumber());
        }
        return this.sqfwFormsummaryNewService.count(cri);
    }

    public Result<?> getCheckRecordById(String id) {
        return Result.data(this.sqfwFormsummaryNewService.fetch(id));
    }

    public FamilyPropertyParamDataDTO getFamilyPropertyParam(String year, String quarter, String householdId) {
        Cnd familyPropertyCnd = Cnd.NEW().and(SqfwFamilyProperty::getQuarter, "=", quarter)
                .and(SqfwFamilyProperty::getYear, "=", year)
                .and(SqfwFamilyProperty::getHouseholdId, "=", householdId);
        SqfwFamilyProperty familyProperty = sqfwFamilyPropertyService.fetch(familyPropertyCnd);

        String paramData = familyProperty.getParamData();
        if (StringUtils.isNotBlank(paramData)) {
            return JSONObject.parseObject(paramData, FamilyPropertyParamDataDTO.class);
        }

        return null;
    }

    /**
     * 获取当前季度的扶贫人员津贴excel信息
     *
     * @param userId 用户id
     * @return 结果
     */
    public PovertyPersonAllowanceExcelInfo getPersonAllowanceExcelInfo(String userId) {
        Sys_user user = sysUserService.fetch(userId);
        // 目前来说导入的文件到街道一级
        YearAndQuarter yearAndQuarter = getCommunityQuarter(new Date());
        Cnd cnd = Cnd.NEW();
        cnd.and(SqfwPovertyUpload::getProvince, "=", user.getProvince())
                .and(SqfwPovertyUpload::getCity, "=", user.getCity())
                .and(SqfwPovertyUpload::getDistrict, "=", user.getDistrict())
                .and(SqfwPovertyUpload::getYear, "=", yearAndQuarter.getYear())
                .and(SqfwPovertyUpload::getQuarter, "=", yearAndQuarter.getQuarter())
                .orderBy(SqfwPovertyUpload::getCreateTime, "desc");
        SqfwPovertyUpload latestPovertyUpload = sqfwPovertyUploadService.fetch(cnd);

        PovertyPersonAllowanceExcelInfo result = new PovertyPersonAllowanceExcelInfo();
        if (latestPovertyUpload == null) {
            result.setYear(yearAndQuarter.getYear());
            result.setQuarter(yearAndQuarter.getQuarter());
            return result;
        }

        BeanUtil.copyProperties(latestPovertyUpload, result);
        return result;
    }

    public String downloadPersonAllowanceExcelTemplate(String userId) {
        YearAndQuarter yearAndQuarter = getCommunityQuarter(new Date());
        return createPovertyPersonAllowanceExcel(yearAndQuarter);
    }

    /**
     * 导入人员津贴excel
     *
     * @param userId 用户id
     * @param file   excel文件
     */
    public void importPersonAllowanceExcel(String userId, String templateUrl, TempFile file) {

        Sys_user sysUser = sysUserService.fetch(userId);

        // 这个方法的主要逻辑为：
        // 1.读取excel中的文件，得到每一个人对一个的补贴金额
        // 2.将人员金额更新到人员表，然后将该季度的人员调查中的信息更新了
        // 3.将家庭财产表的数据更新了
        YearAndQuarter yearAndQuarter = getCommunityQuarter(new Date());
        Map<String, PersonAllowanceExcelInfo> personAllowanceExcelInfoMap = readPersonDataFromExcel(file, yearAndQuarter);

        Set<String> householdIdSet = Sets.newHashSet();
        Trans.exec(() -> {
            for (String idNumber : personAllowanceExcelInfoMap.keySet()) {

                PersonAllowanceExcelInfo personAllowanceExcelInfo = personAllowanceExcelInfoMap.get(idNumber);

                // 首先根据人的身份证号码得到人员信息  并且更新人员信息
                Cnd personCnd = Cnd.NEW();
                personCnd.and(PersonInfo::getIdNumber, "=", idNumber)
                        .and(PersonInfo::getHouseHoldNumber, "=", personAllowanceExcelInfo.getHouseHoldNumber())
                        .and(PersonInfo::getBusinessType, "like", "%脱贫人员%");
                PersonInfo personInfo = personInfoService.fetch(personCnd);

                if (personInfo != null) {
                    // 更新人的信息
                    BeanUtil.copyProperties(personAllowanceExcelInfo, personInfo);
                    personInfo.setUpdateDate(LocalDateTime.now());
                    personInfoService.update(personInfo);

                    householdIdSet.add(personInfo.getHouseholdId());
                }
            }

            if (householdIdSet.size() > 0) {
                for (String householdId : householdIdSet) {
                    // 一户一户的数据进行更新 首先查询出这一户人家所有的已经调查过的人员的数据进行更新
                    SqfwHouseholdRegistrationInfo registrationInfo = sqfwHouseholdRegistrationInfoService.fetch(householdId);

                    List<Date> timeRange = getCommunityQuarterTimeRange(yearAndQuarter);
                    Cnd householdCnd = Cnd.NEW();
                    householdCnd.and(Sqfw_formSummary_new::getFillDate, ">=", timeRange.get(0))
                            .and(Sqfw_formSummary_new::getFillDate, "<=", timeRange.get(1))
                            .and(Sqfw_formSummary_new::getType, "=", SupportBusinessTypeEnum.POVERTY_MONITORING.getName())
                            .and(" param_data ->> 'houseHoldId'", "=", householdId);

                    List<HouseholdIncomeAndPayTypeDTO> householdIPList = Lists.newArrayList();
                    List<Sqfw_formSummary_new> formSummaryNewList = sqfwFormsummaryNewService.query(householdCnd);
                    List<PovertyAlleviationDTO> povertyAlleviationList = Lists.newArrayList();  // 每一个家庭成员提交的数据
                    for (Sqfw_formSummary_new formSummaryNew : formSummaryNewList) {
                        String paramDataStr = formSummaryNew.getParamData();
                        if (StringUtils.isNotBlank(paramDataStr)) {
                            PovertyAlleviationDTO povertyAlleviationDTO = JSONObject.parseObject(paramDataStr, PovertyAlleviationDTO.class);
                            String idNumber = povertyAlleviationDTO.getIdNumber();
                            PersonAllowanceExcelInfo personAllowanceExcelInfo = personAllowanceExcelInfoMap.get(idNumber);
                            if (personAllowanceExcelInfo != null) {
                                BeanUtil.copyProperties(personAllowanceExcelInfo, povertyAlleviationDTO);
                            }
                            povertyAlleviationList.add(povertyAlleviationDTO);

                            if (CollectionUtil.isNotEmpty(povertyAlleviationDTO.getHouseholdIncomeAndPayTypeDTOList())) {
                                householdIPList = povertyAlleviationDTO.getHouseholdIncomeAndPayTypeDTOList();
                            }

                            formSummaryNew.setParamData(JSONObject.toJSONString(povertyAlleviationDTO));
                            formSummaryNew.setUpdateDate(new Date());
                            formSummaryNew.setUpdateBy(userId);
                            sqfwFormsummaryNewService.update(formSummaryNew);
                        }
                    }

                    // 更新这一户人家的所有的家庭收支信息
                    FamilyPropertyParamDataDTO familyPropertyParamDataDTO = createFamilyPropertyParamData(registrationInfo, householdIPList, povertyAlleviationList); // 家庭财产
                    insertOrUpdateFamilyPropertyInfo(userId, familyPropertyParamDataDTO, yearAndQuarter, householdId);
                }

                SysOssService sysOssService = (SysOssService) NutzIocUtils.getBeanByType(SysOssService.class);
                SysOss upload = sysOssService.upload(file);
                // 上传结束之后需要插入一条新的数据
                SqfwPovertyUpload sqfwPovertyUpload = new SqfwPovertyUpload();
                sqfwPovertyUpload.setYear(yearAndQuarter.getYear());
                sqfwPovertyUpload.setQuarter(yearAndQuarter.getQuarter());
                sqfwPovertyUpload.setTemplateUrl(templateUrl);
                sqfwPovertyUpload.setUploadFileUrl(upload.getFileName());
                sqfwPovertyUpload.setUploadFileName(file.getSubmittedFileName());
                sqfwPovertyUpload.setProvince(sysUser.getProvince());
                sqfwPovertyUpload.setCity(sysUser.getCity());
                sqfwPovertyUpload.setDistrict(sysUser.getDistrict());
                sqfwPovertyUpload.setCounty(sysUser.getCounty());
                sqfwPovertyUpload.setCommunity(sysUser.getCommunity());
                sqfwPovertyUpload.setCreateBy(userId);
                sqfwPovertyUpload.setCreateTime(LocalDateTime.now());
                sqfwPovertyUpload.setUpdateId(userId);
                sqfwPovertyUpload.setUpdateTime(LocalDateTime.now());
                sqfwPovertyUploadService.insert(sqfwPovertyUpload);
            }
        });
    }

    /**
     * @param file 文件
     */
    public Map<String, Object> statisticPersonAllowanceExcel(TempFile file) {
        Map<String, Object> resultMap = Maps.newHashMap();
        Map<String, PersonAllowanceExcelInfo> personAllowanceExcelInfoMap = readPersonDataFromExcel(file, getCommunityQuarter(new Date()));

        int dataCount = personAllowanceExcelInfoMap.size();
        int personCount = 0;
        // 首先根据人的身份证号码得到人员信息  并且更新人员信息
        if (personAllowanceExcelInfoMap.size() > 0) {
            Cnd personCnd = Cnd.NEW();
            personCnd.and(PersonInfo::getIdNumber, "in", personAllowanceExcelInfoMap.keySet())
                    .and(PersonInfo::getBusinessType, "like", "%脱贫人员%");
            personCount = personInfoService.count(personCnd);
        }

        resultMap.put("dataCount", dataCount);
        resultMap.put("personCount", personCount);
        return resultMap;
    }


    /**
     * 根据
     *
     * @param yearAndQuarter 年份和季度
     * @return 结果
     */
    private String createPovertyPersonAllowanceExcel(YearAndQuarter yearAndQuarter) {

        String templatePath = getTemplatePathByOS("sqfwV2/povertyMonitoring/allowanceImport.xlsx");
        FileInputStream templateIs = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            templateIs = new FileInputStream(templatePath);

            Map<String, String> sheetParam = Maps.newHashMap();
            String quarterC = "";
            switch (yearAndQuarter.getQuarter()) {
                case "1":
                    quarterC = "一";
                    break;
                case "2":
                    quarterC = "二";
                    break;
                case "3":
                    quarterC = "三";
                    break;
                case "4":
                    quarterC = "四";
                    break;
            }
            List<Date> dateRangeList = getCommunityQuarterTimeRange(yearAndQuarter);
            List<String> monthList = Lists.newArrayList();
            Date startDate = dateRangeList.get(0);
            while (startDate.compareTo(dateRangeList.get(1)) <= 0) {
                monthList.add(DateUtil.format(startDate, "M"));
                startDate = DateUtil.offsetMonth(startDate, 1);
            }

            sheetParam.put("quarterC", quarterC);
            sheetParam.put("_1", monthList.get(0));
            sheetParam.put("_2", monthList.get(1));
            sheetParam.put("_3", monthList.get(2));

            ExcelWriterBuilder builder = EasyExcel.write(outputStream);
            ExcelWriter excelWriter = builder
                    .autoCloseStream(false)
                    .registerConverter(new ExcelPicUrlConverter())
                    .withTemplate(templateIs)
                    .excelType(ExcelTypeEnum.XLSX).build();

            for (int sheetIndex = 0; sheetIndex < 10; sheetIndex++) {
                WriteSheet writeSheet = EasyExcel.writerSheet(sheetIndex).build();
                excelWriter.fill(sheetParam, writeSheet);
                excelWriter.fill(new FillWrapper("data", Lists.newArrayList()), writeSheet);
            }
            excelWriter.finish();
            outputStream.close();

            SysOss sysOss = CommonFormOfficeUtils.uploadFile(outputStream, StrFormatter.format("扶贫转移性收入导入表第{}季度.xlsx", quarterC));

            return sysOss.getFileName();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        } finally {
            IoUtil.close(outputStream);
            IoUtil.close(templateIs);
        }
    }

    /**
     * 从excel中读取数据
     *
     * @param file           文件
     * @param yearAndQuarter 年份
     */
    private Map<String, PersonAllowanceExcelInfo> readPersonDataFromExcel(TempFile file, YearAndQuarter yearAndQuarter) {
        Map<String, PersonAllowanceExcelInfo> personAllowanceExcelInfoMap = Maps.newHashMap();
        try {
            Map<Integer, List<List<String>>> sheetDataListMap = Maps.newTreeMap();
            ExcelUtil.readBySax(file.getInputStream(), -1, createRowHandler(yearAndQuarter, sheetDataListMap));

            for (Integer sheetIndex : sheetDataListMap.keySet()) {
                List<List<String>> sheetRowDataList = sheetDataListMap.get(sheetIndex);
                for (List<String> rowData : sheetRowDataList) {

                    String houseHoldNumber = rowData.get(0);
                    String idNumber = rowData.get(2);
                    String firstMoney = Optional.ofNullable(rowData.get(3)).orElse("0");
                    String secondMoney = Optional.ofNullable(rowData.get(4)).orElse("0");
                    String thirdMoney = Optional.ofNullable(rowData.get(5)).orElse("0");

                    BigDecimal allowance = BigDecimal.ZERO;
                    if (StringUtils.isNotBlank(houseHoldNumber) && StringUtils.isNotBlank(idNumber)) {
                        allowance = allowance.add(new BigDecimal(firstMoney)).add(new BigDecimal(secondMoney)).add(new BigDecimal(thirdMoney));
                    }
                    PersonAllowanceExcelInfo personAllowanceExcelInfo = null;
                    if (personAllowanceExcelInfoMap.containsKey(idNumber)) {
                        personAllowanceExcelInfo = personAllowanceExcelInfoMap.get(idNumber);
                    } else {
                        personAllowanceExcelInfo = new PersonAllowanceExcelInfo();
                        personAllowanceExcelInfo.setIdNumber(idNumber);
                        personAllowanceExcelInfo.setHouseHoldNumber(houseHoldNumber);
                    }

                    if (sheetIndex == 0) {
                        personAllowanceExcelInfo.setMinLivAllow(allowance);
                    }

                    if (sheetIndex == 1) {
                        personAllowanceExcelInfo.setAsstFund(allowance);
                    }

                    if (sheetIndex == 2) {
                        personAllowanceExcelInfo.setPension(allowance);
                    }

                    if (sheetIndex == 3) {
                        personAllowanceExcelInfo.setFamilyPlanAllowance(allowance);
                    }

                    if (sheetIndex == 4) {
                        personAllowanceExcelInfo.setEcoComp(allowance);
                    }

                    if (sheetIndex == 5) {
                        personAllowanceExcelInfo.setPropertyBonus(allowance);
                    }

                    if (sheetIndex == 6) {
                        personAllowanceExcelInfo.setWorkBonus(allowance);
                    }

                    if (sheetIndex == 7) {
                        personAllowanceExcelInfo.setDisabilityAllowance(allowance);
                    }

                    if (sheetIndex == 8) {
                        personAllowanceExcelInfo.setFarmAllowance(allowance);
                    }

                    if (sheetIndex == 9) {
                        personAllowanceExcelInfo.setOtherSubsidies(allowance);
                    }

                    personAllowanceExcelInfoMap.put(idNumber, personAllowanceExcelInfo);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Asserts.fail("读取Excel失败");
        }

        return personAllowanceExcelInfoMap;
    }

    /**
     * excel读取数据的辅助方法
     *
     * @param yearAndQuarter   年份
     * @param sheetDataListMap 数据
     * @return 结果
     */
    private RowHandler createRowHandler(YearAndQuarter yearAndQuarter, Map<Integer, List<List<String>>> sheetDataListMap) {
        return new RowHandler() {
            @Override
            public void handle(int sheetIndex, long rowIndex, List<Object> rowData) {
                // 将会从这一行判断出到底是第几季度的数据
                String excelQuarter = "";
                if (rowIndex == 1 && StringUtils.isNotBlank(yearAndQuarter.getQuarter())) {
                    String title = (String) rowData.get(3);
                    if (title.contains("第一季度")) {
                        excelQuarter = 1 + "";
                    } else if (title.contains("第二季度")) {
                        excelQuarter = 1 + "";
                    } else if (title.contains("第三季度")) {
                        excelQuarter = 3 + "";
                    } else if (title.contains("第四季度")) {
                        excelQuarter = 4 + "";
                    }

                    if (StringUtils.isBlank(excelQuarter) || !excelQuarter.equals(yearAndQuarter.getQuarter()))
                        Asserts.fail("excel格式错误");
                }

                if (rowIndex > 1 && CollectionUtil.isNotEmpty(rowData)) {
                    List<List<String>> sheetList = sheetDataListMap.get(sheetIndex);
                    if (sheetList == null) sheetList = Lists.newArrayList();

                    List<String> rowDataList = Lists.newArrayList();
                    for (Object rowDataItem : rowData) {
                        if (rowDataItem == null) rowDataList.add("");
                        else rowDataList.add(rowDataItem.toString());
                    }

                    if (StringUtils.isNotBlank(rowDataList.get(0))) {
                        sheetList.add(rowDataList);
                        sheetDataListMap.put(sheetIndex, sheetList);
                    }
                }
            }
        };
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class YearAndQuarter {
        private String year;
        private String quarter;
    }

    /**
     * 根据时间获取社区的季度
     *
     * @param date 填写数据时间
     * @return 结果
     */
    public static YearAndQuarter getCommunityQuarter(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);

        // 暂时使用则会中方式来获取，哦，有点蠢但是是可以用的
        // 尖坡村每一年的10-12为第二年的第一季度
        int quarter = 1, quarterYear = year;
        if (month >= 10 && month <= 12) {
            quarterYear = year + 1;
        }

        if (month <= 3) {
            quarter = 2;
        }

        if (month >= 4 && month <= 6) {
            quarter = 3;
        }

        if (month >= 7 && month <= 9) {
            quarter = 4;
        }

        YearAndQuarter yearAndQuarter = new YearAndQuarter();
        yearAndQuarter.setYear(quarterYear + "");
        yearAndQuarter.setQuarter(quarter + "");
        return yearAndQuarter;
    }

    /**
     * 根据年份和季度得到这一季度的开始时间和结束时间
     *
     * @param year    年份
     * @param quarter 季度
     * @return 结果
     */
    public static List<Date> getCommunityQuarterTimeRange(Integer year, Integer quarter) {
        int finalYear = year, startMonth = 0, endMonth = 0;
        if (quarter == 1) {
            finalYear -= 1;
            startMonth = 10;
            endMonth = 12;
        }

        if (quarter == 2) {
            startMonth = 1;
            endMonth = 3;
        }

        if (quarter == 3) {
            startMonth = 4;
            endMonth = 6;
        }

        if (quarter == 4) {
            startMonth = 7;
            endMonth = 9;
        }

        String timeStrFormat = "{}-{}";
        String startTimeStr = StrFormatter.format(timeStrFormat, finalYear, startMonth);
        String endTimeStr = StrFormatter.format(timeStrFormat, finalYear, endMonth);

        Date startTime = DateUtil.beginOfMonth(DateUtil.parse(startTimeStr, "yyyy-M"));
        Date endTime = DateUtil.endOfMonth(DateUtil.parse(endTimeStr, "yyyy-M"));

        return Lists.newArrayList(startTime, endTime);
    }

    /**
     * 获取上一个季度的数据
     *
     * @param date 时间
     * @return 结果
     */
    public static YearAndQuarter getCommunityLastQuarter(Date date) {
        YearAndQuarter communityQuarter = getCommunityQuarter(date);
        int year = Integer.parseInt(communityQuarter.getYear());
        int quarter = Integer.parseInt(communityQuarter.getQuarter());

        YearAndQuarter yearAndQuarter = new YearAndQuarter();
        if (quarter == 1) {
            return null;
        } else if (quarter == 2) {
            yearAndQuarter.setQuarter(1 + "");
            yearAndQuarter.setYear((year - 1) + "");
        } else {
            yearAndQuarter.setYear(year + "");
            yearAndQuarter.setQuarter((quarter - 1) + "");
        }
        return yearAndQuarter;
    }

    public static YearAndQuarter getCommunityLastQuarter(YearAndQuarter communityQuarter) {
        int year = Integer.parseInt(communityQuarter.getYear());
        int quarter = Integer.parseInt(communityQuarter.getQuarter());

        YearAndQuarter yearAndQuarter = new YearAndQuarter();
        if (quarter == 1) {
            return null;
        } else if (quarter == 2) {
            yearAndQuarter.setQuarter(1 + "");
            yearAndQuarter.setYear((year - 1) + "");
        } else {
            yearAndQuarter.setYear(year + "");
            yearAndQuarter.setQuarter((quarter - 1) + "");
        }
        return yearAndQuarter;
    }
}
